angular.module("NTApp").factory('WXService', function(RESTService) {
  var weChat = {};
  var wxConfig = {};
  var listToScan = false;
  var listToDetail = false;

  function setWXConfig(config) {
    wxConfig = config;
  }

  function getWXConfig() {
    return wxConfig;
  }

  function setListToScan(flag) {
    listToScan = flag;
  }

  function getListToScan() {
    return listToScan;
  }

  function setListToDetail(flag) {
    listToDetail = flag;
  }

  function getListToDetail() {
    return listToDetail;
  }

  function getCookieData(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg)) {
      setWeChat(unescape(arr[2]));
    } else {
      setWeChat(null);
    }
  }

  function setWeChat(cookie) {
    if (cookie) {
      weChat.openId = cookie.split('&')[0].split('=')[1];
      weChat.accessToken = cookie.split('&')[1].split('=')[1];
    } else {
      weChat.openId = "";
      weChat.accessToken = "";
    }
  }

  function getWeChat() {
    return weChat;
  }

  function getOnlineToken() {
    var url = "/api/HavcData/GetAccessToken?key=htmlpage";
    return RESTService.get(url).then(function(result) {
      result.data && result.data.appId ? setWXConfig(result.data) : alert('获取微信信息失败，请重新登陆');
      return result.data;
    }, function() {
      alert('获取微信信息失败，请重新登陆');
    });
  }

  function getShareCode(deviceId, physicalDeviceId, openId) {
    var url = "/api/HavcData/GetShareCode?deviceId=" + deviceId + "&physicalDeviceId=" + physicalDeviceId + "&openId=" + openId;
    return RESTService.get(url).then(function(result) {
      return result.data;
    });
  }

  return {
    getWXConfig: getWXConfig,
    getOnlineToken: getOnlineToken,
    getShareCode: getShareCode,
    getCookieData: getCookieData,
    getWeChat: getWeChat,
    setListToScan: setListToScan,
    getListToScan: getListToScan,
    setListToDetail: setListToDetail,
    getListToDetail: getListToDetail
  }
});
